﻿
// Condition: Write a program, that reads from the console an array of N integers and an integer K,
//            sorts the array and using the method Array.BinarySearch() finds the largest number in the array which is ≤ K. 


using System;



class BinarySearchMethod

{
    static void Main(string[] args)
    {

        // declare integer K, integer N, array of N elements 
        Console.Write("Enter K= ");
        int K = int.Parse(Console.ReadLine());
        Console.Write("Enter N= ");
        int N = int.Parse(Console.ReadLine());
        int[] array = new int[N];

        Console.WriteLine();
        Console.WriteLine("Enter elements of array: ");
        for (int i = 0; i < N; i++)
        {
            Console.Write("Element[{0}] = ");
            array[i] = int.Parse(Console.ReadLine());
        }

        // print initial array in console  
        Console.WriteLine("The initial array is:");
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write(array[i]+" ");
        }
        Console.WriteLine();

        // sort the array from smaller to bigger
        Array.Sort(array);

        // print sorted array in console  
        Console.WriteLine("The initial array is:");
        for (int i = 0; i < array.Length; i++)
        {
            Console.Write(array[i] + " ");
        }
        Console.WriteLine();

        // use Binary search method to find the largest element in array which is <=K. 
        int index = Array.BinarySearch(array, K);

        Console.WriteLine();
        if (index >= 0)
        {
            Console.WriteLine("The maximum number <=K is: {0}", array[index]);
        }
        else
        {
            if (index * (-1) - 2 == array.Length - 1)
            {
                Console.WriteLine("The maximum number <=K is: {0}", array[array.Length - 1]);
            }
            else if (index * (-1) - 2 >= 0 && index * (-1) - 2 <= array.Length - 1)
            {
                Console.WriteLine("The maximum number <=K is: {0}", array[index * (-1) - 2]);
            }
            else
            {
                Console.WriteLine("The integer K={0} has value less than the first element of the array.", K);
            }
        }
    }
}

